### 提取ip相关信息
"""
- 接口：https://ip.taobao.com/outGetIpInfo?accessKey=alibaba-inc&ip=要查询的ip地址
- 给一个ip地址，可以通过该接口获取到省份和运营商
- 实现一个ip查询功能
  - 用户输入一个ip地址，将查询到的结果显示给用户
  - 并将结果用以下格式写入到文件：ip,国家,省份,运营商
"""
import requests

# 获取IP地址对应的url信息
def get_ip_info(ip):
    url = f"https://ip.taobao.com/outGetIpInfo?accessKey=alibaba-inc&ip={ip}"
    response = requests.get(url)
    data = response.json()

    if data['code'] == 0:
        ip_info = data['data']
        country = ip_info['country']
        region = ip_info['region']
        isp = ip_info['isp']
        return country, region, isp
    else:
        return None

def main():
    ip = input("请输入要查询的IP地址：")
    ip_info = get_ip_info(ip)

    if ip_info:
        country, region, isp = ip_info
        result = f"IP: {ip}, 国家: {country}, 省份: {region}, 运营商: {isp}"
        print(result)

        # 将得到的数据保存到文件当中
        with open("ip_info.txt", "a") as file:
            file.write(result + "\n")
        print("结果已写入文件。")
    else:
        print("无法获取IP信息。")

if __name__ == "__main__":
    main()